package br.edu.ufcg.dsc.actions.resource;

import org.apache.struts2.config.ParentPackage;
import org.apache.struts2.config.Result;
import org.apache.struts2.dispatcher.ServletRedirectResult;

import br.edu.ufcg.dsc.actions.BaseLoggedAction;
import br.edu.ufcg.dsc.domain.Resource;
import br.edu.ufcg.dsc.domain.resource.Article;
import br.edu.ufcg.dsc.services.ResourceService;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

@Result(name="success", type=ServletRedirectResult.class, value="/index.action?message=Article Successfully Created.")
@ParentPackage("myPackage")
public class UpdateArticleAction extends BaseLoggedAction implements Preparable, ModelDriven<Article>{

	private int resourceId;
	private Article article;
	private static final long serialVersionUID = 1L;

	@Override
	protected String executeIfLogged() throws Exception {
		Resource r = new Resource(article);
		if (ResourceService.find(resourceId) != null)
			r.setId(resourceId);
		
		ResourceService.persist(r);
		
		return ActionSupport.SUCCESS;
	}

	public void prepare() throws Exception {
		Resource resource = ResourceService.find(resourceId);
		if (resource != null)
			article = new Article(resource.getMarc());
		else article = new Article();
	}

	public Article getModel() {
		return article;
	}

}
